package com.zhouchaoqun.web.easyexcel;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author chaoqunzhou
 * @date 2019-09-03 20:36
 */
@Slf4j
public class ExpressBillExccelReader {

    public static void read(MultipartFile excel, int sheetNo, ExpressBillExcelListener excelListener) {
        ExcelReader reader = getReader(excel, excelListener);
        reader.read(new ReadSheet(sheetNo));
    }

    /**
     * 返回 ExcelReader
     */
    private static ExcelReader getReader(MultipartFile excel,
                                         AnalysisEventListener excelListener) {
        String filename = excel.getOriginalFilename();
        if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
            throw new RuntimeException("文件格式错误！");
        }
        InputStream inputStream;
        try {
            inputStream = new BufferedInputStream(excel.getInputStream());
            return EasyExcelFactory.read(inputStream, excelListener).build();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
